<template>
  <div class="app-container">
    <div class="head-container flex-center" style="border-bottom: 1px solid #ddd;">
      <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>字典管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div style="text-align: right">
        <el-button type="primary"
                   plain
                   size="small"
                   v-has-permi="['system:dict:insert']"
                   @click="handleAdd">新增字典</el-button>
        <el-button type="danger"
                   plain
                   size="small"
                   v-has-permi="['system:dict:delete']"
                   :disabled="multiple"
                   @click="handleDelete">删除字典</el-button>
      </div>
    </div>
    <div class="body-container">
      <el-form :model="queryParams"
               ref="queryForm"
               class="queryForm"
               :inline="true"
               v-show="showSearch">
        <el-form-item label="字典查询：" prop="keywords">
          <el-input v-model="queryParams.keywords"
                    placeholder="请输入字典关键字"
                    clearable
                    size="small"
                    @input="getList"/>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <Select :options="statusOptions"
                  v-model="queryParams.status"
                  size="small"
                  placeholder="请选择字典状态"
                  @change="selectQuery" />
        </el-form-item>
      </el-form>
      <el-table v-loading="loading"
                :data="typeList"
                border
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"
                         width="55" />
        <el-table-column label="字典名称"
                         prop="dictName"
                         width="250"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="字典类型"
                         width="250"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope"
                    @click="">
            <el-button type="text"
                       @click="openDictDataDetail(scope.row)">{{scope.row.dictType}}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="状态"
                         prop="status"
                         width="100"
                         :formatter="row => descriptionDictDataStatus(row.status, statusOptions)"/>
        <el-table-column label="备注"
                         prop="remark"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="创建时间"
                         prop="createTime"
                         width="220"
                         :formatter="row => dateFormatter(row, 'createTime')"/>
        <el-table-column label="操作"
                         width="220"
                         class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="small"
                       type="primary"
                       plain
                       v-has-permi="['system:dict:update']"
                       @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button size="small"
                       type="danger"
                       plain
                       v-has-permi="['system:dict:delete']"
                       @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </div>

    <!-- 添加或修改参数配置对话框-字典类型 -->
    <el-dialog :title="title"
               :visible.sync="open"
               :close-on-click-modal="false"
               width="500px"
               append-to-body>
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="100px">
        <el-form-item label="字典名称："
                      prop="dictName">
          <el-input v-model="form.dictName"
                    placeholder="请输入字典名称"/>
        </el-form-item>
        <el-form-item label="字典类型："
                      prop="dictType">
          <el-input v-model="form.dictType"
                    placeholder="请输入字典类型"/>
        </el-form-item>
        <el-form-item label="状态："
                      prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions"
                      :key="dict.dictValue"
                      :label="dict.dictValue">{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注："
                      prop="remark">
          <el-input v-model="form.remark"
                    type="textarea"
                    placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"
                   @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看字典数据的详情信息 -->
    <Dialog :title="dictDataTitle"
            :visible.sync="dictDataShow"
            width="80%"
            :show-footer="false"
            @updateVisible="val => updateVisible(val, 'dictDataShow')">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary"
                     plain
                     size="small"
                     v-has-permi="['system:dict:insert']"
                     @click="handleAddData">新增数据</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger"
                     plain
                     size="small"
                     :disabled="multiple"
                     v-has-permi="['system:dict:delete']"
                     @click="handleDeleteData">删除数据</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading"
                :data="dictDataList"
                border
                @selection-change="handleDataSelection">
        <el-table-column type="selection"
                         width="55"/>
        <el-table-column label="字典类型"
                         width="250"
                         prop="dictType" />
        <el-table-column label="字典标签"
                         width="160"
                         prop="dictLabel" />
        <el-table-column label="字典键值"
                         width="100"
                         prop="dictValue" />
        <el-table-column label="状态"
                         prop="status"
                         width="100"
                         :formatter="row => descriptionDictDataStatus(row.status, statusOptions)"/>
        <el-table-column label="是否默认"
                         width="100"
                         prop="isDefault">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isDefault"
                       active-value="1"
                       inactive-value="0"
                       :disabled="checkPermission()"
                       @change="val => defaultChange(val, scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="备注"
                         prop="remark" />
        <el-table-column label="创建日期"
                         prop="createTime"
                         width="220"
                         :formatter="row => dateFormatter(row, 'createTime')" />
        <el-table-column label="操作"
                         width="220">
          <template slot-scope="scope">
            <el-button size="small"
                       type="primary"
                       plain
                       v-has-permi="['system:dict:update']"
                       @click="handleUpdateData(scope.row)">编辑</el-button>
            <el-button size="small"
                       type="danger"
                       plain
                       v-has-permi="['system:dict:delete']"
                       @click="handleDeleteData(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </Dialog>

    <!-- 字典数据详情弹出层 -->
    <Dialog :title="dictDataDetailTitle"
            :visible.sync="dictDataDetailShow"
            width="500px"
            @cancel="detailCancel"
            @confirm="confirm"
            @updateVisible="val => updateVisible(val, 'dictDataDetailShow')">
      <el-form ref="dataForm" :model="dataForm" :rules="dataRules" label-width="100px">
        <el-form-item label="字典类型：">
          <el-input v-model="dataForm.dictType" disabled/>
        </el-form-item>
        <el-form-item label="数据标签：" prop="dictLabel">
          <el-input v-model="dataForm.dictLabel" placeholder="请输入数据标签"/>
        </el-form-item>
        <el-form-item label="数据键值：" prop="dictValue">
          <el-input v-model="dataForm.dictValue" placeholder="请输入数据键值"/>
        </el-form-item>
        <el-form-item label="显示排序：" prop="dictSort">
          <el-input-number v-model="dataForm.dictSort" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio
              v-for="dict in dictDataOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="dataForm.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
  import Select from '@/components/form/Select'
  import Dialog from '@/components/Dialog'
  import {
    listType,
    getType,
    delType,
    addType,
    updateType,
    exportType
  } from "@/api/system/dict/type"
  import {
    getDictsAll,
    changeDefaultStatus,
    updateData,
    addData,
    getData,
    delData
  } from "@/api/system/dict/data"
  import { checkPermi } from "@/utils/permission"

  export default {
    name: "Dict",
    components: {Select, Dialog},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 字典表格数据
        typeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 字典类型的使用状态字典
        statusOptions: [],
        // 字典数据的使用状态字典
        dictDataOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          keywords: undefined,
          status: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          dictName: [
            {required: true, message: "字典名称不能为空", trigger: "blur"}
          ],
          dictType: [
            {required: true, message: "字典类型不能为空", trigger: "blur"}
          ]
        },
        // 字典数据弹出层
        dictDataShow: false,
        // 字典数据弹出层标题
        dictDataTitle: '',
        // 字典数据列表
        dictDataList: [],
        // 字典类型
        dictType: '',
        // 字典数据详情弹出层标题
        dictDataDetailTitle: '',
        // 字典数据详情弹出层
        dictDataDetailShow: false,
        // 字典数据表单
        dataForm: {},
        // 字典数据表单验证规则
        dataRules: {
          dictLabel: [
            {required: true, message: "字典标签不能为空", trigger: "blur"}
          ],
          dictValue: [
            {required: true, message: "字典键值不能为空", trigger: "blur"}
          ]
        },
        // 选中的字典数据详情
        dataIds: []
      }
    },
    created() {
      this.getList()
      // 字典类型的使用状态
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data
      })
      // 字典数据的使用状态
      this.getDicts('sys_dict_data_disable').then(res => {
        this.dictDataOptions = res.data
      })
    },
    methods: {
      /** 查询字典类型列表 */
      getList() {
        this.loading = true
        listType(this.queryParams).then(response => {
          this.typeList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          dictId: undefined,
          dictName: undefined,
          dictType: undefined,
          status: "1",
          remark: undefined
        }
        this.dataForm = {
          dictLabel: undefined,
          dictValue: undefined,
          dictSort: 0,
          status: "1",
          remark: undefined
        }
        this.resetForm("form")
        this.resetForm("dataForm")
      },
      checkPermission() {
        return !checkPermi(['system:dict:update'])
      },
      /** 下拉框选择 */
      selectQuery(val) {
        if (val) this.queryParams.status = val
        else delete this.queryParams.status
        this.getList()
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加字典类型"
      },
      /** 多选框字典类型列表的数据 */
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.dictType)
        this.multiple = !selection.length
      },
      /** 选中字典数据列表的数据 */
      handleDataSelection(selection) {
        this.dataIds = selection.map(item => item._id)
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const dictType = row.dictType || this.ids
        getType(dictType).then(response => {
          this.form = response.data
          this.open = true
          this.title = "修改字典类型"
        })
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form._id != undefined) {
              updateType(this.form).then(response => {
                this.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addType(this.form).then(response => {
                this.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const dictType = row.dictType ? [row.dictType] : this.ids
        this.$confirm('是否确认删除字典编号为"' + dictType + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delType(dictType)
        }).then(() => {
          this.getList()
          this.msgSuccess("删除成功")
        }).catch(() => {
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有类型数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true
          return exportType(queryParams)
        }).then(response => {
          this.download(response.msg)
          this.exportLoading = false
        }).catch(() => {
        })
      },
      getDictDataList() {
        getDictsAll(this.dictType).then(res => {
          this.dictDataList = res.data
          this.loading = false
        })
      },
      /** 打开字典数据列表 */
      openDictDataDetail(row) {
        this.dictDataShow = true
        this.dictDataTitle = row.dictName
        this.loading = true
        this.dictType = row.dictType
        this.getDictDataList()
      },
      /** 默认值切换 */
      defaultChange(val, row) {
        changeDefaultStatus(row).then(() => {
          this.$message.success('保存成功')
          this.getDictDataList()
        })
      },
      /** 新增字典数据 */
      handleAddData() {
        this.reset()
        this.dictDataDetailShow = true
        this.dictDataDetailTitle = '添加字典数据'
        this.dataForm.dictType = this.dictType
      },
      /** 修改字典数据 */
      handleUpdateData(row) {
        this.reset()
        const id = row._id || this.dataIds
        getData(id).then(res => {
          this.dataForm = res.data
          this.dictDataDetailShow = true
          this.dictDataDetailTitle = '修改字典数据'
        })

      },
      /** 删除字典数据 */
      handleDeleteData(row) {
        const ids = row._id ? [row._id] : this.ids
        this.$confirm('是否确认删除字典编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delData(ids)
        }).then(() => {
          this.getDictDataList()
          this.msgSuccess("删除成功")
        }).catch(() => {
        })
      },
      detailCancel() {
        this.dictDataDetailShow = false
        this.reset()
      },
      /** 字典数据详情弹框确认 */
      confirm() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            if (this.dataForm._id != undefined) {
              updateData(this.dataForm).then(res => {
                this.msgSuccess('修改成功')
                this.dictDataDetailShow = false
                this.getDictDataList()
              })
            } else {
              addData(this.dataForm).then(res => {
                this.msgSuccess('新增成功')
                this.dictDataDetailShow = false
                this.getDictDataList()
              })
            }
          }
        })
      }
    }
  }
</script>
